package com.unis.controller.system;

import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.util.ValidateUtil;
import com.unis.controller.BaseController;
import com.unis.dto.ResultDto;
import com.unis.logger.TargetLogger;
import com.unis.model.system.Account;
import com.unis.service.system.AccountService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/8/008.
 */

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private AccountService accountService;

    @TargetLogger("010701")
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto queryUserList(@RequestParam Map<?, ?> paramMap){
        int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = accountService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @TargetLogger("010702")
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping("/excel")
    public void exportUserList(HttpServletResponse response,@RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = EXPORT_SIZE;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = accountService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportUser"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<Account> export = new ExportBeanExcel<Account>();
            String[] headers = {"账号","姓名","身份证号","警号","联系方式","所属机构"};
            String[] cols = {"username","xm","idno","jh","lxfs","jgmc"};

            export.exportExcel("user",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping("/page")
    public String page() {
        return "system/user/page";
    }

    @TargetLogger("0104")
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType, Account user) throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        String msg = null;
        if (user!=null){
            if (StringUtils.equalsIgnoreCase(curdType,"insert")){
                 msg = ValidateUtil.valid(user);
                 if (StringUtils.isNotBlank(msg)){
                     logger.error("valid insert Account is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                 accountService.insert(user);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
                if(StringUtils.isNotBlank(user.getPk())) {
                    accountService.delete(user.getPk());
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete Account is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
                msg = ValidateUtil.valid(user);
                if (StringUtils.isNotBlank(msg)){
                    logger.error("valid update Account is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
                accountService.updateByPrimaryKey(user);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
        resultMap.put("msg",msg);
        return resultMap;
    }

    @TargetLogger("0105")
    @RequestMapping("/changePwd")
    @RequiresAuthentication
    @ResponseBody
    public Map<String,String> changePwd(String old_password,String password,String conf_password) throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        String msg = accountService.changePwd(old_password, password, conf_password);
        resultMap.put("msg",msg);
        return resultMap;
    }

    @TargetLogger("0106")
    @RequestMapping("/resetPwd")
    @RequiresAuthentication
    @ResponseBody
    public Map<String,String> resetPwd() throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        accountService.resetPwdByInfo();
        resultMap.put("msg","密码重置成功。");
        return resultMap;
    }
    @TargetLogger("020501")
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping( "/roleList")
    @ResponseBody
    public List<Map<String,String>> queryRoleList(String userPk){
        try {
            return accountService.queryRoleListByPage(userPk);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @TargetLogger("020502")
    @RequiresPermissions("ROLE_XTGL_USER")
    @RequestMapping("/grantRole")
    @ResponseBody
    public Map<String,String> grantRole(String userPk,String checkedRoles){
        Map<String,String> resultMap = new HashMap<>();
        String msg = null;
        if(StringUtils.isNotBlank(userPk)){
            try {
                accountService.updateGrantRole(userPk, checkedRoles);
                msg="角色分配成功";
                resultMap.put("msg",msg);
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new RequestEntityTooLargeException(e.getMessage());
            }

        }else{
            msg="信息未填写";
            logger.error(msg);
        }
        resultMap.put("msg",msg);
        return resultMap;
    }
}
